package com.iyue.user;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;

import com.iyue.Sns;
import com.iyue.SpringHelper;
import com.iyue.common.bean.HttpAPI;
import com.iyue.common.bean.JsonResponse;
import com.iyue.core.pojo.UserAccount;
import com.iyue.core.service.CoreBiz;
import com.iyue.framework.BaseAction;
import com.iyue.framework.util.GsonUtil;
import com.iyue.servlet.taglibs.Functions;
import com.iyue.sso.bean.SSOInfo;
import com.iyue.sso.helper.SSOUtil;
import com.iyue.sys.pojo.SysProvince;
import com.iyue.user.helper.UserUtil;
import com.iyue.user.pojo.UserBasic;
import com.iyue.user.pojo.UserInviteSign;
import com.iyue.user.pojo.UserProtect;
import com.iyue.user.service.UserBiz;
import com.iyue.util.ValidCode;

/**
 * 《网站注册》实现类
 * 
 * @author 孙晓晔
 * @version $Id: Reg.java,v 1.1 2010/10/14 17:07:17 fresh Exp $
 */
public class Reg extends UserUtil {
	/**
	 * 注册成功
	 */
	public static final Integer REG_SUCCESS = 1;
	/**
	 * 注册失败 - 系统出错
	 */
	public final static Integer REG_FAILURE = 2;

	/*
	 * 注册 - 第一步
	 */
	public ActionForward aa(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		// if (isLogin(request)) {
		// return new ActionRedirect(
		// url(request, "portal.do", "&do=Portal.my"));
		// }
		// hangl add
		List<SysProvince> province = Functions.provinces();
		request.setAttribute("provinces", province);
		
		String account = request.getParameter("account");
		if (StringUtils.isBlank(account)) {
			request.setAttribute("msg", "请输入账号");
			return action.display(request, response, "reg/aa");
		}

		request.setAttribute("account", account);
		String password = request.getParameter("password");
		if (StringUtils.isBlank(password)) {
			request.setAttribute("msg", "请输入密码！");
			return action.display(request, response, "reg/aa");
		}

		password = password.trim();
		if (!password.matches("(\\d|\\w){6,16}")) {
			request.setAttribute("msg", "密码必须要以字母或数字的组合！");
			return action.display(request, response, "reg/aa");
		}

		if (password.length() > 16) {
			request.setAttribute("msg", "输入密码过长，请重新输入！");
			return action.display(request, response, "reg/aa");
		}

		String password2 = request.getParameter("password2");
		if (StringUtils.isBlank(password2)) {
			request.setAttribute("msg", "请输入再次确定密码！");
			return action.display(request, response, "reg/aa");
		}

		if (!password.equals(password2)) {
			request.setAttribute("msg", "再次确定密码与密码不一致，请重新输入！");
			return action.display(request, response, "reg/aa");
		}

		String code = request.getParameter("vcode");
		if (code == null || code.length() <= 0) {
			request.setAttribute("msg", "验证码不正确！");
			return action.display(request, response, "reg/aa");
		}

		String vkey = request.getParameter("vkey");
		if (vkey == null || vkey.length() <= 0) {
			request.setAttribute("msg", "验证码不正确！");
			return action.display(request, response, "reg/aa");
		}

		if (!ValidCode.isValid(vkey, code)) {
			request.setAttribute("msg", "验证码不正确！");
			return action.display(request, response, "reg/aa");
		}

		int cp = checkPasswd(password);
		if (cp > UserAccount.PASSWORD_REGULAR) {
			if (cp == UserAccount.PASSWORD_NULL) {
				request.setAttribute("msg", "密码不能为空！");
			}
			if (cp == UserAccount.PASSWORD_LENGTH) {
				request.setAttribute("msg", "输入密码过短，请重新输入！");
			}
			if (cp == UserAccount.PASSWORD_SIMPLE) {
				request.setAttribute("msg", "密码过于简单，请重新输入！");
			}

			return action.display(request, response, "reg/aa");
		}

		CoreBiz biz = (CoreBiz) SpringHelper.getBean("CoreBiz");
		Integer username = biz.getUsernameByAccount(account);
		if (username != null) {
			request.setAttribute("msg", "该账号已经注册！");
			return action.display(request, response, "reg/aa");
		}

		String src = request.getParameter("src");
		if (StringUtils.isBlank(src)) {
			src = "02101";
		}

		UserAccount user2 = new UserAccount();
		user2.setAccount(account);
		user2.setPassword(password);
		user2.setStatus(UserAccount.STATUS_OK);
		String mobile = request.getParameter("mobile");
		if (!StringUtils.isBlank(mobile) && isMobile(mobile)) {
			user2.setMobile(mobile);
		}

		String nickname = request.getParameter("nickname");
		if (!StringUtils.isBlank(nickname)) {
			user2.setNickname(nickname);
		} else {
			user2.setNickname("");
		}
		String ret = register_api(Sns.url_register_service, GsonUtil.getGson()
				.toJson(user2));
		if (ret == null) {
			request.setAttribute("msg", "注册失败，请稍后再试!");
			return action.display(request, response, "reg/aa");
		}

		if (ret != null && ret.equals(JsonResponse.CODE_PARAM_REG)) {
			request.setAttribute("msg", "账号已经注册,请重新输入!");
			return action.display(request, response, "reg/aa");
		}

		if (ret != null && ret.equals(JsonResponse.CODE_PARAM_NICKNAME)) {
			request.setAttribute("msg", "该昵称已使用,请重新输入!");
			return action.display(request, response, "reg/aa");
		}

		if (ret != null && ret.equals(JsonResponse.RESULT_FAILURE)) {
			request.setAttribute("msg", "注册失败，请稍后再试!");
			return action.display(request, response, "reg/aa");
		}

		user2 = GsonUtil.getGson().fromJson(ret, UserAccount.class);
		if (user2 == null) {
			request.setAttribute("msg", "注册失败，请稍后再试!");
			return action.display(request, response, "reg/aa");
		}

		username = user2.getUsername();

		UserBasic basic = new UserBasic();
		String provCode = "";
		String areaCode = "";
		basic.setUsername(username);
		basic.setProvince(provCode);
		basic.setCity(areaCode);

		UserBiz user_biz = (UserBiz) SpringHelper.getBean("UserBiz");
		user_biz.save_basic(basic);

		String sign = request.getParameter("sign");
		if (StringUtils.isNotBlank(sign)) {
			invite_sign(username, sign);
		}

		sso_login(request, response, username);

		String msg = "恭喜你注册成功，你的账号为：" + user2.getAccount() + ",密码为："
				+ user2.getPassword();
		Redirect(request, response, "/portal.do?do=Portal.layout" + "&msg="
				+ Functions.encode(msg));
		return null;
	}

	private void sso_login(HttpServletRequest request,
			HttpServletResponse response, Integer username) {
		Long timeSpan = 60 * 60 * 24 * 7l;
		SSOInfo info = SSOUtil.getSSOInfo(username, timeSpan);

		SSOUtil.login(request, response, info);
	}

	/**
	 * 用户注册
	 * 
	 * @param username
	 * @return
	 */
	public static String register_api(String url, String json) {
		if (StringUtils.isBlank(json)) {
			return null;
		}

		JsonResponse res = HttpAPI.getJsonRes(url, json);
		if (res == null) {
			return null;
		}

		String error = res.getErrCode();
		if (error != null && error.equals(JsonResponse.CODE_PARAM_REG)) {
			return JsonResponse.CODE_PARAM_REG;
		}

		if (error != null && error.equals(JsonResponse.CODE_PARAM_NICKNAME)) {
			return JsonResponse.CODE_PARAM_REG;
		}

		if (!StringUtils.isBlank(error)) {
			return JsonResponse.RESULT_FAILURE;
		}

		String result = res.getResult();
		if (StringUtils.isEmpty(result)) {
			return JsonResponse.RESULT_FAILURE;
		}

		return result;
	}

	/**
	 * 绑定邮箱，为了找回密码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @param action
	 * @return
	 * @throws Exception
	 */
	public ActionForward password_email(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		if (!isLogin(request)) {
			return action.display(request, response, "login");
		}

		String email = request.getParameter("email");
		if (!isEmail(email)) {
			request.setAttribute("msg", "请输入正确的email地址");
			return action.display(request, response, "password_email");
		}

		Integer username = u(request);
		UserProtect up = new UserProtect();
		up.setUsername(username);
		up.setEmail(email);
		Date now = new Date();
		up.setCreatetime(now);
		up.setModifytime(now);

		UserBiz biz = (UserBiz) SpringHelper.getBean("UserBiz");
		biz.save_protect(up);

		request.setAttribute("msg", "操作成功！");

		return new ActionRedirect(url(request, "portal.do", "do=Portal.my"));
	}

	/**
	 * 邀请好友标记
	 * 
	 * @param username
	 * @param sign
	 */
	private void invite_sign(Integer username, String sign) {
		UserBiz biz = (UserBiz) SpringHelper.getBean("UserBiz");
		Integer aa = biz.getSign(sign);
		if (aa > 0) {
			return;
		}

		UserInviteSign user = new UserInviteSign();
		user.setUsername(username);
		user.setSign(sign);
		user.setCreatetime(new Date());
		biz.save_invite_sign(user);
	}

	/**
	 * 判断是否是数字
	 * 
	 * @param num
	 * @return
	 */
	public static boolean isNumeric(String num) {
		if (num == null) {
			return false;
		}

		return num.matches("\\d{1,}");
	}
}
